﻿function Socket_Push(param) {
    var self = this;
    if (param != undefined && param.key != undefined) {

        $("script").each(function () {
            var src = $(this).attr("src")
            if (src && src.lastIndexOf("Socket_Push") >= 0) {
                var signalrpath = src.substr(0, src.lastIndexOf("Socket_Push")) + "signalr/dist/browser/signalr.min.js";
                $("head").append("<script src='" + signalrpath + "'></script>")
                return false
            }
        })
        param.receivefunc = param.receivefunc || "recive";
        param.hubpath = param.hubpath || "/hub";

        self.conn = new signalR.HubConnectionBuilder()
            .withUrl(param.hubpath + "?key=" + param.key)
            .build()
        self.conn.on(param.receivefunc, function (obj) {
            if ($.isFunction(param.receive))
                param.receive(obj)
        });
        self.conn.onclose(function () {
            if ($.isFunction(param.onclose))
                param.onclose();
        })
        self.conn.start().then(function (data) {
        }).catch(function (err) {
            return console.error(err.toString());
        });
    }
}
Socket_Push.prototype = {
    conn: null,
    send: function (param) {
        var self = this;
        self.conn.invoke("Execute", param.action, param.data)
            .then(function (data) {
                if ($.isFunction(param.success))
                    param.success(data);
            })
            .catch(function (err) {
                if ($.isFunction(param.error))
                    param.error(err);
                return console.error(err.toString());
            });

    }
}
